<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\WeChatJSSDK;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use App\Admin\SampleInfo;
use App\Admin\Contract;
use Illuminate\Support\Facades\Storage;
use phpDocumentor\Reflection\File;
use QrCode;
use Log;

class SampleInfoController extends Controller
{
    //增加打印次数
    public function addSamplePrint(Request $request){
        $bar_code = $request->bar_code;
        if (!$bar_code) {
            return 0;
        }
        try{
            DB::table('a_sample_info')->where('bar_code',$bar_code)->increment('print_passed_card_times',1,['print_passed_card_last_time'=>date('Y-m-d H:i:s')]);
        }catch(\Exception $e){
            return $e->getMessage();
        }
        return 1;
    }
    //批次生产RFID
    public function setRFID(){
        $contract_id = request('contract_id');
        $status = Contract::where('id',$contract_id)->value('status');
        if ($status && $status > 8) {
            return '审批中无法操作！';
        }
        $sampleInfoIds = SampleInfo::where(['contract_id'=>$contract_id,'gqj_ID'=>''])->pluck('id');
        $noCount = 0;
        $setSys = getCache('setting');
        foreach ($sampleInfoIds as $sampleInfoId) {
            request()->offsetSet('id',$sampleInfoId);
            $RFIDdata = $this->generateGqjID();
            if (is_string($RFIDdata)) {
                return $RFIDdata;  // 错误信息
            }
            $RFIDdata = $RFIDdata->getData(true);
            $rfid = $RFIDdata['head'].$RFIDdata['body'].$RFIDdata['foot'].$RFIDdata['gqjID_check'];
            $res = 0;
            if($setSys['gqjID_count'] == 24){
                $rfid = $setSys['gqj_com_code'].$setSys['gqj_scode'].$rfid;
            }
            if (strlen($rfid) == 18 || strlen($rfid) ==  24) {
                $up = [
                    'gqj_ID' => $rfid,
                    'pipe_code' => sprintf('%01d', $RFIDdata['body']),
                ];
                $res = DB::table('a_sample_info')->where('id',$sampleInfoId)->update($up);
            }
            $noCount += $res ? 0 : 1;
        }
        return $noCount > 0 ? "有<span style='color:red;'>{$noCount}</span>个RFID生产失败！" : '操作成功！';
    }
    /*不再提醒预警到期*/
    public function notNotice($barCode) {
        $barCode = trim($barCode, ',');
        $barCode = explode(',', $barCode);
        $res = DB::table('a_sample_info')->whereIn('bar_code', $barCode)->update(['notice' => 0]);
        return out($res, '操作成功！', $barCode);
    }

    /*不合格照片，斗臂车照片*/
    public function photoList() {
        $sql = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->leftJoin('a_contract as c', 'a.contract_id', '=', 'c.id')->where('a.res', '=', 2)->where('a.non_photo', '=', '');
        if(config('constant.app_name') === 'ShanXiShiJiZhongShi') {
            $sql = $sql->where('c.batchNum', '>', '210007');
        }
        $nonlist = $sql->orderBy('a.test_time', 'desc')->select('a.id', 'a.bar_code', 'b.tool_name', 'c.client_name')->get();
        $zunon = [];
        foreach($nonlist as $item) {
            $zunon[substr($item->bar_code, 0, - 3)][] = $item;
        }
        $sql = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->leftJoin('a_contract as c', 'a.contract_id', '=', 'c.id')->where('b.tool_id', '=', 47)->where('a.photo', '=', '');
        if(config('constant.app_name') === 'ShanXiShiJiZhongShi') {
            $sql = $sql->where('c.batchNum', '>', '210007');
        }
        $doulist = $sql->orderBy('a.test_time', 'desc')->select('a.id', 'a.bar_code', 'c.client_name')->get();
        $zudou = [];
        foreach($doulist as $item) {
            $zudou[substr($item->bar_code, 0, - 3)][] = $item;
        }
        return view('admin.sampleInfo.photoList', compact('zunon', 'zudou'));
    }

    /*不合格照片，斗臂车照片---提交*/
    public function photoListSub(Request $request) {
        if($request->isMethod('POST')) {
            $post_data = $request->only(['photo', 'non_photo']);
            $post_data['pos'] = request('pos','');
            $id = $request->detail_id;  //detail_id  => sample_info_id
            $res = $this->photoDeal($id, $post_data);
            if(is_string($res)) {
                return out(0, $res);
            }
            $post_data = $res;
            $result = SampleInfo::where('id', $id)->update($post_data);
            return $result > 0 ? 1 : 0;
        }
    }

    private function photoDeal($id, $post_data) {
        $sampleInfo = SampleInfo::find($id);
        $uploadcon = new UploadController();
        $photos = [
            'photo'     => request('photo', ''),   //照片（斗臂车）
            'non_photo' => request('non_photo', ''), //不合格照片
        ];
        foreach($photos as $column => $val) {
            if(isset($post_data[$column]) && trim($post_data[$column]) !== '') {
                $dir = $column === 'non_photo' ? 'sample_info/non' : ($column === 'photo' ? 'sample_info' : '');
                $posParam = data_get($post_data,'pos',''); //默认不合格照
                $pos = $posParam ? '_'.$posParam : ''; //外观照+_1
                $res = $uploadcon->render('img', [
                    'dir' => $dir, 'file' => $post_data[$column], 'filename' => $sampleInfo['bar_code'].$pos, 'text' => $sampleInfo['bar_code'], 'rotate' => 1, 'aspect_ratio' => 3/4 //高宽比
                ]);
                if($res['code'] === 1) {
                    if($sampleInfo[$column] !== '') {
                        DB::table('a_sample_info')->where('bar_code', $sampleInfo['bar_code'])->update([$column => '']);
                    }
                    $path = $res['data']['path'];
                    //山东淄博千恒如果是不合格照片上传分为外观和细节照，所以这里判断下
                    if($column == 'non_photo'){
                        $pathOld = $sampleInfo->non_photo;
                        if ($posParam !== '') {
                            $paths = explode(',',$pathOld);
                            data_set($paths,$posParam,$path);
                            $paths = [
                                0=>data_get($paths,0,''), //不合格照
                                1=>data_get($paths,1,''),  //外观照
                            ];
                            $path = implode(',',$paths);
                        }
                    }
                    unset($post_data['pos']);
                    $post_data[$column] = $path;
                }
                else {
                    return $res['msg'];
                }
            }
        }
        return $post_data;
    }

    /*备注模板列表*/
    public function remarkList() {
        $list = DB::table('a_remark_temp')->where('table', 'sample_info')->orderBy('sort', 'desc')->get();
        if(request()->expectsJson()) {
            $data['data'] = $list;
            return response()->json($data);
        }
        return view('admin.sampleInfo.remark.list');
    }

    /*备注模板删除*/
    public function remarkDel() {
        $res = DB::table('a_remark_temp')->where('id', request()->id)->where('table', 'sample_info')->delete();
        return $res;
    }

    /*备注模板添加*/
    public function remarkAdd() {
        $data = request()->only('content');
        request()->validate(['content' => 'required',]);
        $data['table'] = 'sample_info';
        $data['sort'] = time();
        $res = DB::table('a_remark_temp')->insertGetId($data);
        return $res ? '添加成功' : '添加失败';
    }

    /*列表数据*/
    public function listData($para) {
        // dd($para);
        $sql = DB::table('a_sample_info as a')
                ->leftJoin('a_contract as b', 'b.id', '=', 'a.contract_id')
                ->leftJoin('a_contract_gaiyao as c', 'c.id', '=', 'a.contract_gaiyao_id')
                ->leftJoin('a_tool as d', 'd.id', '=', 'c.tool_id')
                ->leftJoin('a_tool_class as e', 'e.id', '=', 'd.tool_class_id');
        //           $sql = $sql ->where('a.res', '>', 0);
        if($para) {
            if(isset($para['searcho'])) {
                $searcho = $para['searcho'];
                foreach($searcho as $val) {
                    $name = $val['name'];
                    $value = str_replace(array(" ","　","\t","\n","\r"), '', $val['value']);
                    if($value !== '') {
                        if(strpos($name, 'test_time') !== false) {
                            $pos = substr($name, -1, 1);
                            if($pos == 0) {
                                $sql = $sql->whereDate('a.test_time', '>=', $value);
                            }
                            if($pos == 1) {
                                $sql = $sql->whereDate('a.test_time', '<=', $value);
                            }
                        }
                        else {
                            $fuhao = substr($val['name'], 1, 1);
                            $table = $fuhao === '_' ? substr($val['name'], 0, 1) : 'a';
                            $column = $fuhao === '_' ? substr($val['name'], 2) : $val['name'];
                            $sql = $sql->where($table.'.'.$column, $value);
                        }
                    }
                }
            }
            $search = isset($para['search']['value']) ? $para['search']['value'] : '';
            $para_col = isset($para['columns']) ? $para['columns'] : [];
            if(strlen($search) > 0) {
                //判断是否有搜索条件
                //以下匿名函数实现的功能，laravel手册中叫参数分组
                //                dd($search,$para_col);
                $sql = $sql->where(function($query) use ($search, $para_col) {
                    foreach($para_col as $val) {
                        if(isset($val['searchable']) && $val['searchable'] == 'true') {
                            if($val['data'] && $val['data'] != null) {
                                $fuhao = substr($val['data'], 1, 1);
                                $table = $fuhao === '_' ? substr($val['data'], 0, 1) : 'a';
                                $column = $fuhao === '_' ? substr($val['data'], 2) : $val['data'];
                                $query->orWhere($table.'.'.$column, 'like', '%'.escape_like_str($search).'%');
                            }
                        }
                    }
                });
            }
        }
        $isSearch = isset($para['is_search']);
        if($isSearch) {
            if($para['is_search'] == 0) {
                $searchdate = date('Y-m-d 00:00:00', strtotime('-6 months'));
                $sql = $sql->whereDate('a.ctime', '>', $searchdate);
            }
        }
        $count = $sql->count();
        $perpagecount = request()->length; //导出数据时候没有长度限制
        $offset = request()->start;
        // dd($offset,$perpagecount);
        if ($perpagecount) {
            $sql = $sql->offset($offset)->limit($perpagecount);
        }
        $sql = $sql->select('a.*', 'b.client_name as b_client_name', 'b.entrusted_company as b_entrusted_company', 'b.batchNum as b_batchNum', 'b.client_contact as b_client_contact', 'b.client_tel as b_client_tel', 'b.deadline as b_deadline', 'c.voltage as c_voltage', 'c.class as c_class', 'c.unit as c_unit', 'c.std_num as c_std_num', 'c.item_names as c_item_names', 'c.tool_name as c_tool_name', 'c.tool_id as c_tool_id', 'c.item_ids as c_item_ids', 'c.std_id as c_std_id', 'e.name as e_name', 'b.paid_status as b_paid_status', 'b.paid_at as b_paid_at', 'b.money as b_money', 'b.paid_num as b_paid_num','c.remark as c_remark','c.cycle as c_cycle');
        
        $order = isset($para['order']) ? $para['order'] : '';
        if($order) {
            //判断是否启用排序
            foreach($order as $val) {
                $column = $para['columns'][intval($val['column'])]['data'];
                if($column) {
                    $sql = $sql->orderBy($column, $val['dir']);
                }
            }
        }
        $sql = $sql->orderBy('a.ctime', 'desc');
        $sqldata = $sql->get()->toArray();
        // dd($sqldata);
        foreach($sqldata as $k => $item) {
            $itemData = DB::table('a_sample_info as a')
                ->leftJoin('a_contract_gaiyao as c', 'c.id', '=', 'a.contract_gaiyao_id')
                ->leftJoin('a_item_data as f', function($join) {
                    $join->on('f.sample_info_id', '=', 'a.id')->where('f.res', '=', 0);
                })
                ->leftJoin('a_testitem as g', 'g.id', '=', 'f.item_id')
                ->leftJoin('a_status_time as h', 'h.contract_id', '=', 'a.contract_id')
                ->leftJoin('a_std_tool_rel as i', function($join) {
                    $join->on('i.tool_id', '=', 'c.tool_id')->on('i.std_id', '=', 'c.std_id');
                })->where('a.id',$item->id)
                ->select('g.name as g_name', 'h.key as h_key', 'i.cycle as i_cycle', 'h.approve_end as h_approve_end', 'h.sendback_end as h_sendback_end')
                ->get();
            // dd($itemData);
            $itemDataKeyVals = [];
            foreach($itemData as $item2){
                foreach ($item2 as $keyitem2 => $valueitem2) {
                    $itemDataKeyVals[$keyitem2][] = $valueitem2;
                }
            }
            foreach($itemDataKeyVals as $itemDataKey => $itemDataKeyVal){
                $item->$itemDataKey = implode('，',array_unique($itemDataKeyVal));
                if ($itemDataKey == 'i_cycle' && $item->c_cycle != '') {
                    $item->$itemDataKey = $item->c_cycle;
                }
            }
            $sqldata[$k] = $item;
        }
        $data = [];
        $data['data'] = $sqldata;
        $data['iTotalRecords'] = $data['iTotalDisplayRecords'] = $count;
        return $data;
    }

    public function exportList(Request $request, $search) {
        $app_name = config('constant.app_name');
        $className = "App\\Http\\Controllers\\Admin\\ExportList\\{$app_name}Controller";
        if (!class_exists($className)) {
            $className = "App\\Http\\Controllers\\Admin\\ExportList\\PublicController";
        }
        if (!class_exists($className)) {
            return '类不存在';
        }
        // dd($className);
        $exportReport = new $className();
        return $exportReport->export($request,$search);
    }

    public function list(Request $request) {
        $data = [];
        if($request->expectsJson()) {
            $param = $request->all();
            $data = $this->listData($param);
            $data['start_date'] = isset($param['start_date']) ? $param['start_date'] : '';
            return response()->json($data);
        }
        else {
            $report_num_pre = DB::table('setting')->where('id', '1')->value('report_num_pre'); //报告编号前缀
            $data['report_num_pre'] = $report_num_pre;
            $data['client_code_classes'] = DB::table('a_client_code_class')->get(); //客户编码分类
            $app_name = config('constant.app_name');
            $setting_info = DB::table('setting')->find('1'); //设置信息
            $client = DB::table('a_client')->pluck('entrusted_company','name')->toArray();
            try{
                return view('admin.sampleInfo.list.'.$app_name, compact('data','setting_info','client'));
            }catch(\Exception $e){
                return view('admin.sampleInfo.list', compact('data', 'setting_info','client'));
            }
        }
    }

    /* 样品基本信息批量添加 */
    public function add(Request $request) {
        //获取批次的id
        $id = $request->id;
        //获取批次信息
        $batch_info = DB::table('a_contract')->select('batchNum', 'status')->where('id', $id)->first();
        //获取批次状态
        $batch_status = $batch_info->status;
        if($batch_status != 0) {
            return '此批次已提交';
        }

        //获取批次号
        $batch_num = $batch_info->batchNum;
        //获取批次的概要信息
        $data_gaiyao = DB::table('a_contract_gaiyao')->where('contract_id', $id)->get();
        if($data_gaiyao->isEmpty()) {
            return '此批次内容是空的';
        }
        /* foreach ($data_gaiyao as $val) {
            $count = $val->count;
            $index = $val->index;
            $srt_item = $val->item_ids;
            $arr_item = explode(",", $srt_item); //字符串 --> 数组

            for ($i = 0; $i < $count; $i++) {
                $str_suf = sprintf('%03d', $index++);
                $bar_code = $batch_num.$str_suf;
                //构建要插入的数据
                $data_insert = [
                    'bar_code' => $bar_code,
                    'contract_id' => $id,
                    'contract_gaiyao_id' => $val->id,
                    'key' => str_random(6) //用六位随机字符串作为密码
                ];
                //插入数据    insertGetId 返回 ID 值
                $insert_id = DB::table('a_sample_info')->insertGetId($data_insert);

                $data_item = [];
                foreach ($arr_item as $vv) {
                    # code...
                    //构建要插入的数据
                    $data_item[] = [
                        'contract_id' => $id,
                        'contract_gaiyao_id' => $val->id,
                        'sample_info_id' => $insert_id,
                        'item_id' => $vv,
                    ];
                }
                //插入数据    insert 返回true 或 false
                $result = DB::table('a_item_data')->insert($data_item);
            }
        } */

        // if ($result) {
        //改变批次的状态
        $data_status = ['status' => '1'];
        $result3 = DB::table('a_contract')->where('id', $id)->update($data_status);
        // }
        return $result3 ? '1' : '0';
    }

    /* 合同详细信息展示 */
    public function index(Request $request) {
        //获取批次的id
        $id = $request->id;
        //获取批次的详细信息
        $data = DB::table('a_contract_detail')->where('a_contract_id', $id)->get();
        return view('admin.contractDetail.index', compact('data'));
    }

    //写入工器具铭牌信息
    private function upGqjPlate($idsAry,$plates){
        $sampleData = DB::table('a_sample_info as a')
                        ->leftJoin('a_contract_gaiyao as b','a.contract_gaiyao_id','=','b.id')
                        ->whereIn('a.id',$idsAry)->select('a.bar_code_1st','a.bar_code','b.tool_name')->get();
        $changed = false;
        foreach($sampleData as $item){
            $bar_code_1st = $item->bar_code_1st ?: $item->bar_code;
            $doesntExist = DB::table('a_gqj_plate')->where('bar_code_1st',$bar_code_1st)->doesntExist();
            if($plates){
                if($doesntExist){
                    $data = ['bar_code_1st'=>$bar_code_1st,'tool_name'=>$item->tool_name,'plate'=>json_encode(array_values($plates))];
                    $res = DB::table('a_gqj_plate')->insert($data);
                }else{
                    $res = DB::table('a_gqj_plate')->where('bar_code_1st',$bar_code_1st)->update(['plate'=>json_encode(array_values($plates))]);
                }
                $changed = $res ? true : false;
            }
        }
        return $changed;
    }

    /* 样品基本信息展示+信息录入 */
    public function indexInfoLuru(Request $request) {
        if($request->expectsJson()) {
            if($request->isMethod('POST')) {
                $idsAry = explode(',', $request->detail_id);
                //其他操作   
                $post_data = $request->only(['self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'sample_status', 'photo', 'non_photo', 'batch_num_custom','force_scrap_date','place','third_id','self_tool_name']);
                // dd($post_data);
                if(request('force_scrap_date','') == '/'){
                    unset($post_data['force_scrap_date']);
                }
                if(count($idsAry) > 1) {
                    $post_data = array_filter($post_data);
                    if($post_data === []) {
                        return 0;
                    }
                }
                else {
                    if(isset($request->gqj_ID) && $request->gqj_ID !== '') {
                        if(strstr($request->gqj_ID_head, '?')) {
                            return out(0, 'ID码错误！');
                        }
                        $gqj_ID_foot = $request->gqj_ID_foot ?: '';
                        $setSys = getCache('setting'); //系统设置（setting_sys）
                        $post_data['gqj_ID'] = $gqjId = $request->gqj_ID_head.$request->gqj_ID.$gqj_ID_foot;
                        if($setSys['gqjID_count'] == 24) {
                            $post_data['gqj_ID'] = $setSys['gqj_com_code'].$setSys['gqj_scode'].$post_data['gqj_ID'].$request->gqjID_check;
                            if($request->gqjID_check != $this->getCheckCode(substr($post_data['gqj_ID'], 0,23))) {
                                return out(0, '校验错误！');
                            }
                        }
                        if($request->is_scan == 0) {     //不是扫描添加
                            $repeat = DB::table('a_sample_info')->where('gqj_ID', $gqjId)->first();
                            if($repeat && $repeat->id != $request->detail_id) {
                                return out(0, 'ID码重复');
                            }
                        }
                        $post_data['pipe_code'] = sprintf('%01d', $request->gqj_ID);
                    }
                    if(isset($request->bar_code_1st)) {
                        $post_data['bar_code_1st'] = $request->bar_code_1st ?: $request->bar_code;
                    }
                }
                if(isset($post_data['photo']) || isset($post_data['non_photo'])) {
                    $sampleInfo = SampleInfo::find($request->detail_id);
                    $uploadcon = new UploadController();
                    if(isset($post_data['photo']) && trim($post_data['photo']) !== '') {
                        $res = $uploadcon->render('img', [
                            'dir' => 'sample_info', 'file' => $post_data['photo'], 'filename' => $sampleInfo['bar_code'], 'text' => $sampleInfo['bar_code'], 'rotate' => 1, 'aspect_ratio' => 3/4  //高宽比
                        ]);
                        if($res['code'] === 1) {
                            if($sampleInfo['photo'] !== '') {
                                DB::table('a_sample_info')->where('bar_code', $sampleInfo['bar_code'])->update(['photo' => '']);
                            }
                            $post_data['photo'] = $res['data']['path'];
                        }
                    }
                    if(isset($post_data['non_photo']) && trim($post_data['non_photo']) !== '') {
                        $res = $uploadcon->render('img', [
                            'dir' => 'sample_info/non', 'file' => $post_data['non_photo'], 'filename' => $sampleInfo['bar_code'], 'text' => $sampleInfo['bar_code'], 'rotate' => 1, 'aspect_ratio' => 3/4 //高宽比
                        ]);
                        if($res['code'] === 1) {
                            if($sampleInfo['non_photo'] !== '') {
                                DB::table('a_sample_info')->where('bar_code', $sampleInfo['bar_code'])->update(['non_photo' => '']);
                            }
                            $post_data['non_photo'] = $res['data']['path'];
                        }
                        else {
                            return out(0, $res['msg']);
                        }
                    }
                }
                $post_data['is_luru'] = 1;
                // dd($post_data);
                $result = SampleInfo::whereIn('id', $idsAry)->update($post_data);
                return $result > 0 ? 1 : 0;
                ;
            }
            else {
                //获取批次的id
                $id = $request->id;
                $data = DB::table('a_sample_info as a')
                    ->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')
                    ->select('a.*', 'b.tool_name', 'b.voltage', 'b.class','b.tool_id')
                    ->leftJoin('a_tool as c', 'b.tool_id', '=', 'c.id')
                    ->select('a.*', 'b.tool_name', 'b.voltage', 'b.class','b.tool_id')
                    ->where('a.contract_id', $id)
                    ->orderByRaw('a.is_luru asc, a.bar_code asc')->get();
                $result['data'] = $data;
                return response()->json($result);
            }
        }
        else {
            $contract_id = $request->id;
            $contractInfo = DB::table('a_contract')->select('client_name')->find($contract_id);
            $gaiyao = DB::table('a_contract_gaiyao')->where('contract_id', $contract_id)->selectRaw('tool_name,
                    Sum(count) AS count')->groupBy('tool_name')->get(); 
            $enable_tool_ID = DB::table('setting')->where('id', '1')->value('enable_tool_ID');
            $places = DB::table('setting_sys')->where('key', 'test_place')->value('value');
            $places = $places ? explode(',', $places) : '';
            $signPackage = null;

            try {
                if(config('constant.wechat_app_id')){
                    $WXJSSDK = new WeChatJSSDK();
                    $signPackage = $WXJSSDK->getSignPackage();
                }
            } catch(\Exception $exception) {}
            $factorys = DB::table('a_factory')->orderBy('sort', 'desc')->pluck('name');
            $setSys = getCache('setting'); //系统设置（setting_sys）
            $settingCon = new SettingController();
            if($setSys['gqjID_pro']){
                $gqjID_18_pro = $settingCon->RFID_18($setSys['gqjID_pro']);
            }else{
                $gqjID_18_pro = [
                    'serial'=>0,
                    'sub_count'=>0,
                ];
            }
        
            return view('admin.sampleInfo.indexInfoLuru', compact('contractInfo', 'enable_tool_ID', 'places', 'signPackage', 'factorys', 'gaiyao', 'setSys', 'gqjID_18_pro'));
        }
    }
    //获取工器具铭牌属性
    private function getToolPlates($gyData){
        $toolNames = [];
        foreach($gyData as $item){
            $toolNames[] = $item->tool_name;
        }
        $toolIds = array_unique($toolNames);
        $plateNames = DB::table('a_tool_plate as a')
            ->leftJoin('a_tool as b','a.tool_id','=','b.id')
            ->whereIn('b.name',$toolNames)
            ->select('a.*','b.name as tool_name')->orderBy('formulas','asc')->get();
        $toolPlates = [];
        foreach($plateNames as $item){
            $toolPlates[$item->tool_name][] = (array)$item;
        }
        return $toolPlates;
    }

    //获取样品铭牌属性
    public function gqjPlate(){
        $sampleId = request('sampleId');
        $sample = DB::table('a_sample_info')->where('id',$sampleId)->first();
        $barcode1st = $sample->bar_code_1st;
        $data['plate'] = DB::table('a_gqj_plate')
            ->where('bar_code_1st',$barcode1st)
            ->first();
        $data['energyStd'] = DB::table('a_energy_std')
            ->where('id',$sample->energy_std_id)
            ->first();
        return response()->json($data);
    }

    /* 样品基本信息展示+结果录入 */
    public function indexResLuru(Request $request) {
        if ($request->isMethod('post')) {
            if($request->editDate == 1){
                // dd($request->all());
                $date = $request->date;
                if ($date) {
                    $sample_ids = $request->input('sample_ids');
                    if(!$sample_ids){
                       return 0; 
                    }
                    $item = $request->item;
                    $itemDataCon = new ItemDataController();
                    foreach ($sample_ids as $sample_id) {
                        if ($item == 1) {
                            DB::table('a_item_data')->where('sample_info_id',$sample_id)->update(['utime'=>date('Y-m-d H:i:s',strtotime($date))]);
                        }
                        $itemDataCon->updateTestTime_NextTime($sample_id);
                    }
                    return 1;
                }else{
                    return 0;
                }
            }
        }
        $id = $request->id;
        $contractInfo = DB::table('a_contract')->find($id);
        try{
            $setting = getCache('setting');
            $enable_tool_ID = $setting['setting']->enable_tool_ID;
        }catch(\Throwable $e){
            $enable_tool_ID = 0;
        }

        $manager_id = auth('admin')->user()->id;
        $where = ['contract_id'=>$id];
        if (!isAdmin()) {
            $where['manager_id'] = $manager_id;
        }
        $sample_info_id = DB::table('a_item_data')->where($where)->pluck('sample_info_id')->toArray();
        $arr_sample_info_id = array_unique($sample_info_id);
        if (!$arr_sample_info_id) {
            $res_data = [];
        }else{
            $res_data = SampleInfo::with('contract_gaiyao:id,tool_name,voltage,class,third_id')
                    ->where('contract_id',$id)
                    ->whereIn('id',$arr_sample_info_id)
                    ->get()->toArray();
            // dd($result['data']->toArray());
            if(auth('admin')->user()->role_id === 1) {
                $sample_commit_data = DB::table('a_item_data')->distinct()->select('sample_info_id', 'commit')->where('contract_id', $id)->get();
            }
            else {
                $sample_commit_data = DB::table('a_item_data')->distinct()->select('sample_info_id', 'commit')->where('manager_id', $manager_id)->where('contract_id', $id)->get();
            }
            // dd($sample_commit_data->toArray());
            $sample_commit_data = $sample_commit_data->toArray();
            foreach($res_data as $key => $val) {
                foreach($sample_commit_data as $v) {
                    if($val['id'] === $v->sample_info_id) {
                        $res_data[$key]['status'] = $v->commit;
                    }
                }
            }
        }
        
        return view('admin.sampleInfo.indexResLuru', compact('contractInfo','enable_tool_ID','res_data'));
    }

    //发布提交主题
    private function upTopicSampleSubmitCount($num) {
        return false;
        if(config('constant.is_lan')){
            return false;
        }
        $count = cache('sample_submit_noread_count', 0);
        $count += $num;
        cache()->forever('sample_submit_noread_count', $count);
        $client = new \Mosquitto\Client();
        $client->setCredentials('sample_sub_user', 'sample_sub_user');
        $client->connect("0.0.0.0", 1883, 60);
        $client->onPublish(function() use ($client) {
            $client->disconnect();
        });
        // dd(domain());
        $client->publish('/'.domain().'/sample_info/submit/count', $count);
    }

    /* 样品基本信息展示(条形码打印) */
    public function indexPrintBarCode(Request $request) {
        //获取批次的id
        $id = $request->id;
        //获取批次的客户名称
        $client_name = DB::table('a_contract')->where('id', $id)->value('client_name');
        $setting_info = DB::table('setting_sys')->where('key', 'print_bar_code')->value('value'); //设置信息
        $setting_info = json_decode($setting_info, true);
        if(!isset($setting_info['is_remote_RFID'])) {
            $setting_info['is_remote_RFID'] = "";
        }
        if(!isset($setting_info['remote_ip_RFID'])) {
            $setting_info['remote_ip_RFID'] = "";
        }

        $barCode_JS_file = 'Common'; //前端加载的 打印条形码的 js 文件
        $app_name = config('constant.app_name');
        # 如果项目的条形码格式有个性化需求，就把这个项目的 APP_NAME 放到 $arr_app_name 数组中
        $barCode_JS_file_path = "admin/static/myfolder/js/printBarCodeContent_{$app_name}.js";
        if(file_exists($barCode_JS_file_path)) {
            $barCode_JS_file = $app_name;
        }
        $RFID_JS_file = '';
        if(file_exists("admin/static/myfolder/js/printRFID{$app_name}.js")) {
            $RFID_JS_file = $app_name;
        }
        $data = DB::table('a_sample_info as a')->leftJoin('a_contract_gaiyao as b', 'a.contract_gaiyao_id', '=', 'b.id')->leftJoin('a_tool as c', 'b.tool_id', '=', 'c.id')->leftJoin('a_tool_class as d', 'c.tool_class_id', '=', 'd.id')->where('a.contract_id', $id)->select('a.id', 'a.bar_code', 'a.guige_xinghao', 'a.gqj_ID', 'b.tool_name', 'b.class', 'b.voltage', 'd.name as class_name')->orderBy('a.bar_code', 'asc')->get();
        return view('admin.sampleInfo.indexPrintBarCode', compact('client_name', 'setting_info', 'barCode_JS_file', 'data','RFID_JS_file'));
    }

    /**
     * 获取该样品的所有分类与电压
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function getVoltageClass(){
        if(request()->expectsJson()) {
            $id = request('id', 0);
            if($id === 'undefined') {
                return out(1);
            }
            $gaiyaoId = DB::table('a_sample_info')->where('id',$id)->pluck('contract_gaiyao_id');
            $stdId_toolId = DB::table('a_contract_gaiyao')->select('std_id','tool_id')->where('id',$gaiyaoId[0])->first();
            $voltageClass = DB::table('a_voltage_class')->where('std_id',$stdId_toolId->std_id)->where('tool_id',$stdId_toolId->tool_id)->get();
            $str = '';
            foreach($voltageClass as $key=>$val){
                $str .= "<option value='{$val->val}'> {$val->val} </option>";
            }
            if(!$str){
                $str .= "<option value='/'> / </option>";
            }
            $data['str'] = $str;
            return response()->json($data);
        }
    }

    /* 生成工器具ID */
    public function generateGqjID() {
        // sleep(3);
        if(request()->expectsJson()) {
            $id = request('id', 0);
            if($id === 'undefined') {
                return out(1);
            }
            $sql = "SELECT
                        A.id,
                        A.bar_code,
                        A.contract_id,
                        B.tool_name,
                        B.sub_count,
                        B.voltage
                    FROM
                        a_sample_info AS A
                        LEFT JOIN a_contract_gaiyao AS B ON A.contract_gaiyao_id = B.id
                    WHERE
                        A.id = :id";
            $sample_info = DB::select($sql, ['id' => $id]);
            $sample_info = array_shift($sample_info);
            $gqj_ID_8 = DB::table('a_contract')->where('id', $sample_info->contract_id)->value('gqj_ID');
            if(!$gqj_ID_8) {
                $gqj_ID_8 = "????????";
            }

            $voltage_code = DB::table('a_code_vol_map')->where('voltage', $sample_info->voltage)->value('code'); //电压等级码
            if($voltage_code === null) {
                $voltage_code = DB::table('a_code_vol_map')->where('voltage', str_replace(' ', '', $sample_info->voltage))->value('code'); //电压等级码
                if($voltage_code === null) {
                    $voltage_code = "??";
                }
            }

            $samplename_code = (int)DB::table('a_code_samplename_map')->where('name', $sample_info->tool_name)->value('code'); //工具类别码
            if($samplename_code === null) {
                $samplename_code = "???";
            }
            $data['head'] = $gqj_ID_8.$voltage_code.$samplename_code;

            $setSys = getCache('setting');
            $settingCon = new SettingController();
            $gqjID_18_pro = $settingCon->RFID_18($setSys['gqjID_pro']);

            #region 数量+序号
            $sub_count = $sample_info->sub_count;
            if($sub_count === 1) {
                $index = '1';
            }
            else { //还没用到
                $index = substr($sample_info->bar_code, -1);
            }
            // dd($gqjID_18_pro);
            $data['foot'] = $gqjID_18_pro['sub_count'] ? $sample_info->sub_count.$index : '';
            #endregion  数量+序号
            #region 流水号
            $serial_len = data_get($gqjID_18_pro,'serial',3);
            if($index === '1') {
                # 该样品只含一件，或含多件且当前是第一件
                $gqj_ID_max = DB::table('a_sample_info')->where('gqj_ID','like',$data['head'].'%')->selectRaw("max(gqj_ID) as gqj_ID_max")->value('gqj_ID_max');
                $serial_max = (int)substr($gqj_ID_max,'-'.($gqjID_18_pro['sub_count']+$gqjID_18_pro['sub_num']+$serial_len),$serial_len);
                $data['body'] = sprintf('%0'.$serial_len.'d', $serial_max + 1);
            }
            else {  //还没用到
                $first_barcode = substr_replace($sample_info->bar_code, "1", - 1);
                $pipe_code = DB::table('a_sample_info')->where('bar_code', $first_barcode)->value('pipe_code'); //流水码
                $data['body'] = sprintf('%0'.$serial_len.'d', $pipe_code);
                if(!trim($data['body'], '0')) {
                    $data['body'] = sprintf('%?'.$serial_len.'s', $pipe_code);
                }
                // dd($first_barcode);
            }
            if (strlen($data['body']) != $serial_len) {
                return '样品数量超过可容量！';
            }
            #endregion 流水号
            #region 生成工器具ID-最后一位校验码
            $data['gqjID_check'] = $setSys['gqjID_count'] == 24 ? $this->getCheckCode($setSys['gqj_com_code'].$setSys['gqj_scode'].$data['head'].$data['body'].$data['foot']) : '';
            #endregion
           return response()->json($data); 
        }
    }

    /* 生成工器具ID-最后一位校验码 */
    public function getCheckCode($bef23) {
        if(strlen($bef23) !== 23 || strstr($bef23, '?')) {
            return '编码错误,校验失败！';
        }
        //校验码
        $he = 0;
        for($i = 0; $i < strlen($bef23); $i ++) {
            $wi = $i%2 === 0 ? 3 : 1;    //加权因子
            $ai = $bef23[$i];
            $he += $wi*$ai;  //将各位数字与 其相对应的加 权值依次相乘 , 并将乘积相加，得 出和数
        }
        //用和数除以模 数 10，得出余数，根 据余数获取相 应的校验码
        $check = (10 - $he%10)%10;
        return $check;
    }

    //单个提交，结果录入后
    public function oneSubmit(Request $request) {
        $id = $request->id; //sample_info 的 id
        $manager_id = auth('admin')->user()->id;

        if(DB::table('a_item_data')->where(['sample_info_id' => $id, 'manager_id' => $manager_id])->whereIn('commit', [- 1, 0])->count() === 0) {
            return '没有可以提交的数据';
        }

        //先判断此样品的 所属主检人 的所有项目 是否都录入结果
        $sql = "SELECT
                    count( 1 ) = 0  AS res_over
                FROM
                    a_item_data
                WHERE
                    sample_info_id = :sample_info_id
                    AND manager_id = :manager_id
                    AND res =2";
        //如果结果全部录入返回1，否则返回0
        $res_over = DB::select($sql, ['sample_info_id' => $id, 'manager_id' => $manager_id]);
        if(!$res_over[0]->res_over) {
            //结果未全部录入，返回'2'
            return '2';
        }

        //更新a_item_data表的 commit 字段
        $res1 = DB::table('a_item_data')->where('sample_info_id', $id)->where('manager_id', $manager_id)->update(['commit' => '1']);
        if($res1) {
            //增加提交次数
            DB::table('a_sample_info')->where('id', $id)->increment('submit_times', 1);
            //初次提交时间
            DB::table('a_sample_info')->where('id', $id)->whereNull('submit_time')->update(['submit_time' => date('Y-m-d H:i:s')]);
        }

        //判断当前样品的所有试验项目是否都提交
        $item_count = DB::table('a_item_data')->where('sample_info_id', $id)->count();
        $commit_count = DB::table('a_item_data')->where('sample_info_id', $id)->where('commit', '1')->count();
        if($item_count === $commit_count) {
            //当前样品的所有项目都已经提交，更新a_sample_info表的 status0 字段
            DB::table('a_sample_info')->where('id', $id)->update(['status0' => '1']);
        }

        // 提交后检查当前批次 未提交的记录数
        $res2 = DB::table('a_item_data')->where('contract_id', $request->batch_id)->where('commit', '0')->count();
        //如果为0，说明本批次已全部提交，此时改变contract的状态
        if($res2 === 0) {
            DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);

            //查询此批次是否记录过试验完成的时间
            $test_end = DB::table('a_status_time')->where('contract_id', $request->batch_id)->value('test_end');
            if(!$test_end) {
                # 如果没记录过，就记录试验完成的时间
                $now_time = date("Y/m/d H:i:s"); //当前时间
                DB::table('a_status_time')->where('contract_id', $request->batch_id)->update(['test_end' => $now_time]);
            }
        }
// dd($res1);
        if($res1 >= 0 ) {
            $this->upTopicSampleSubmitCount(1);
        }
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //批量提交，结果录入后
    public function batchSubmit(Request $request) {
        $arr_ids = $request->checkID; //sample_info 的id ，是个数组
        $manager_id = auth('admin')->user()->id;
        $b = false; //一个样品的结果是否全部录入的标志

        foreach($arr_ids as $id) {
            //先判断此样品的 所属主检人 的所有项目 是否都录入结果
            $sql = "SELECT
                        count( 1 ) = 0  AS res_over
                    FROM
                        a_item_data
                    WHERE
                        sample_info_id = :sample_info_id
                        AND manager_id = :manager_id
                        AND res =2";
            //如果结果全部录入返回1，否则返回0
            $res_over = DB::select($sql, ['sample_info_id' => $id, 'manager_id' => $manager_id]);
            if(!$res_over[0]->res_over) {
                //结果未全部录入
                $b = true;
                continue;
            }

            //更新a_item_data表的 commit 字段
            $res1 = DB::table('a_item_data')->where('sample_info_id', $id)->where('manager_id', $manager_id)->update(['commit' => '1']);
            if($res1) {
                //增加提交次数
                DB::table('a_sample_info')->where('id', $id)->increment('submit_times', 1);
                //初次提交时间
                DB::table('a_sample_info')->where('id', $id)->whereNull('submit_time')->update(['submit_time' => date('Y-m-d H:i:s')]);
            }

            //判断当前样品的所有试验项目是否都提交
            $item_count = DB::table('a_item_data')->where('sample_info_id', $id)->count();
            $commit_count = DB::table('a_item_data')->where('sample_info_id', $id)->where('commit', '1')->count();
            if($item_count === $commit_count) {
                //当前样品的所有项目都已经提交，更新a_sample_info表的 status0 字段
                DB::table('a_sample_info')->where('id', $id)->update(['status0' => '1']);
            }

        }

        // 提交后检查当前批次 未提交的记录数
        $res2 = DB::table('a_item_data')->where('contract_id', $request->batch_id)->where('commit', '0')->count();
        //如果为0，说明本批次已全部提交，此时改变contract的状态
        if($res2 === 0) {
            DB::table('a_contract')->where('id', $request->batch_id)->update(['status' => '8']);

            //查询此批次是否记录过试验完成的时间
            $test_end = DB::table('a_status_time')->where('contract_id', $request->batch_id)->value('test_end');
            if(!$test_end) {
                # 如果没记录过，就记录试验完成的时间
                $now_time = date("Y/m/d H:i:s"); //当前时间
                DB::table('a_status_time')->where('contract_id', $request->batch_id)->update(['test_end' => $now_time]);
            }
        }

        if($b) {
            return "存在结果未全部录入的样品，请检查";
        }
        $this->upTopicSampleSubmitCount(count($arr_ids));
        return "批量提交成功";
    }

    /* 样品基本信息展示（审核） */
    public function indexCheck(Request $request) {
        //获取批次的id
        $id = $request->id;
        if($request->expectsJson()) {
            // ajax提交
            if($request->isMethod('POST')) {
                //
            }
            else {
                $sql = "SELECT DISTINCT
                            `a`.*,
                            `b`.`tool_name`,
                            `b`.`voltage`,
                            `b`.`class`,
                            c.back_count
                        FROM
                            `a_sample_info` AS `a`
                        LEFT JOIN `a_contract_gaiyao` AS `b` ON `a`.`contract_gaiyao_id` = `b`.`id`
                        LEFT JOIN (
                            SELECT
                                sample_info_id,
                                COUNT(1) AS back_count
                            FROM
                                `a_reject_log`
                            GROUP BY
                                sample_info_id
                        ) AS c ON `a`.`id` = `c`.`sample_info_id`
                        WHERE
                            `a`.`contract_id` = :id
                        ORDER BY
                            `bar_code` ASC";

                $result['data'] = DB::select($sql,['id'=>$id]);
                return response()->json($result);
            }
        }
        else {
            //非 ajax提交
            $contractInfo = DB::table('a_contract')->select('id', 'client_name')->find($id);
            //按工器具分组和计算数量
            $sql = "select tool_id,tool_name,sum(count) as tool_count from a_contract_gaiyao where contract_id=$id GROUP BY tool_id,tool_name";
            $tool_group = DB::select($sql);
            return view('admin.sampleInfo.indexCheck', compact('contractInfo','tool_group'));
        }
    }

    /* 样品基本信息展示（查看） */
    public function viewCheck(Request $request) {
        //获取批次的id
        $id = $request->id;

        if($request->expectsJson()) {
            // ajax提交
            if($request->isMethod('POST')) {
                //
            }
            else {
                $sampleInfo = new SampleInfo();
                $result = $sampleInfo->getTableData($request->all(), 'contract_gaiyao:id,tool_name,voltage,class', ['bar_code', 'asc'], [['contract_id', '=', $id]]);
                return response()->json($result);
            }
        }
        else {
            //非 ajax提交
            $contractInfo = DB::table('a_contract')->select('id', 'client_name')->find($id);

            return view('admin.sampleInfo.viewCheck', compact('contractInfo'));
        }
    }

    /* 样品基本信息展示（打印合格证） */
    public function indexPrintPassedCard(Request $request) {
        if($request->expectsJson()) {
            if($request->isMethod('POST')) {
                //
            }
            else {
                //获取批次的id
                $id = $request->id;
                // $contractDetail = new ContractDetail();
                // $result = $contractDetail->getTableData($request->all(), 'manager:id,realname,partner', null, [['a_contract_id', '=', $id]]);
                // return response()->json($result);
                $data = DB::table('a_sample_info as a')
                        ->leftJoin('a_contract_gaiyao as b', 'b.id', '=', 'a.contract_gaiyao_id')
                        ->leftJoin('a_tool as c', 'c.id', '=', 'b.tool_id')
                        ->leftJoin('a_tool_class as d', 'd.id', '=', 'c.tool_class_id')
                        ->leftJoin('a_contract as e', 'e.id', '=', 'a.contract_id')
                        ->leftJoin('a_code2_samplename_map', 'a_code2_samplename_map.name', '=', 'b.tool_name')
                        ->select('a.*', 'b.tool_name', 'b.std_num', 'b.class', 'b.voltage', 'e.name_ABC', 'e.created_at', 'a_code2_samplename_map.code', 'd.name as class_name','b.remark')
                        ->where('e.id', $id)
                        ->orderBy('bar_code', 'asc')
                        ->get();
                $jsonData['data'] = $data;
                return response()->json($jsonData);
            }
        }
        else {
            $contractInfo = DB::table('a_contract')->select('client_name','batchNum')->find($request->id);
            $setting_sys = getCache('setting');
            $setting_info = $setting_sys['setting']; //设置信息
            $hasAqm = DB::table('a_contract_gaiyao')->where('contract_id', $request->id)->where('tool_id', 1)->exists();    //判断是否有安全帽
            return view('admin.sampleInfo.indexPrintPassedCard', compact('contractInfo', 'setting_info', 'setting_sys', 'hasAqm'));
        }
    }

    /**
     * 批量生成合格证模板
     * batchPrintLaser
     */
    public function batchPrintLaser(Request $request){
        $ids = $request->sids;
        if(!$ids) return '';
        $ids = json_decode($ids);
        //获取批次编号
        $contract = DB::table('a_sample_info as a')
            ->leftjoin('a_contract as b','a.contract_id','=','b.id')
            ->select('batchNum')
            ->where('a.id',$ids[0])
            ->first();
        //获取公司名称
        $setting_sys = getCache('setting');
        $setting_info = $setting_sys['setting']; //设置信息

        //循环ids
        foreach($ids as $id){
            //样品信息
            $data = DB::table('a_sample_info as a')
                ->leftJoin('a_contract_gaiyao as b', 'b.id', '=', 'a.contract_gaiyao_id')
                ->leftJoin('a_tool as c', 'c.id', '=', 'b.tool_id')
                ->leftJoin('a_tool_class as d', 'd.id', '=', 'c.tool_class_id')
                ->leftJoin('a_contract as e', 'e.id', '=', 'a.contract_id')
                ->leftJoin('a_code2_samplename_map', 'a_code2_samplename_map.name', '=', 'b.tool_name')
                ->select('a.*', 'b.tool_name', 'b.std_num', 'b.class', 'b.voltage', 'e.name_ABC', 'e.created_at', 'a_code2_samplename_map.code', 'd.name as class_name','b.remark')
                ->where('a.id', $id)
                ->orderBy('a.bar_code', 'asc')
                ->first();

            //加载模板
            $template_file = './storage/ExcelTemplate/激光打标机.xls'; //考虑到兼容Linux，斜杠用“/”
            if(!file_exists($template_file)) {
                return '模板文件不存在';
            }
            //生成模板
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file); //读取模板文件
            $worksheet = $spreadsheet->getSheet(0); //按索引获取表单，从 0 开始
            /* ---------------- 二维码 start-------------------- */
            $domain = $request->server('HTTP_HOST'); //域名
            $url_name = 'http://'.$domain."/viewRes?id={$id}&k={$data->key}";
            $qr_code_path = "./QrCodeImage/QrCodeSample{$id}";

            $qrCode = QrCode::format('png');
            $qrCode = $qrCode->size(150);
            $qrCode = $qrCode->margin(0);
            $qrCode->generate($url_name, $qr_code_path);

            $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
            $drawing->setPath($qr_code_path);//图片的路径
            $drawing->setHeight(93);//高度 保持宽高比
            $drawing->setOffsetX(5);
            $drawing->setCoordinates('A2');//指定位置
            $drawing->setCoordinates('F8');//指定位置

            // 要将上述图形添加到工作表，请使用以下代码段。PhpSpreadsheet创建绘图和工作表之间的链接：
            $drawing->setWorksheet($worksheet);
            /* ---------------- 二维码 end-------------------- */
            /*----------------- 内容页 ------------------------*/
            $hege = $data->res?'合 格 证':'不 合 格';
            $guige_xinghao = $data->voltage.''.$data->guige_xinghao; //规格型号
            $test_time = date('Y年m月d日',strtotime($data->test_time));
            $next_time = date('Y年m月d日',strtotime($data->next_time));

            $worksheet->getCell('B2')->setValue($setting_info->name_pass);
            $worksheet->getCell('B3')->setValue($hege);
            $worksheet->getCell('B5')->setValue($data->tool_name);
            $worksheet->getCell('B6')->setValue($guige_xinghao);
            $worksheet->getCell('B7')->setValue($data->bar_code);
            $worksheet->getCell('B8')->setValue($test_time);
            $worksheet->getCell('B9')->setValue($next_time);
            $worksheet->getCell('B10')->setValue($data->tester_names); //送检单位

            $worksheet->setTitle($data->bar_code.'合格证');
            /*---------------保存-----------------*/
            $file_name = "passedCard{$data->bar_code}.xls";
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
            $writer->setPreCalculateFormulas(false); //禁用公式预先计算
            //storage
            $storeFile = "reports/{$contract->batchNum}/{$file_name}";
            $disk = Storage::disk('public');
            $disk->put($storeFile,''); //创建路径
            $path = $disk->path($storeFile);
            $writer->save($path);
            //为了防止内存泄露，建议用完手动清理
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet);
            unlink($qr_code_path);//删除二维码图片  节省硬盘空间
        }

        //生成zip压缩包
        $diskk = Storage::disk('public');
        $dir = "reports/{$contract->batchNum}";
        $fileList = $diskk->files($dir);

        $storeFile = "reports/{$contract->batchNum}.zip";   //压缩包目录
        $pathh = $diskk->path($storeFile);                  //在storage文件中的路径
        $zip = new \ZipArchive();
        $zip->open($pathh,\ZipArchive::CREATE);        //打开压缩包
        foreach($fileList as $file){
            $pathfile = $diskk->path($file);                //在storage文件中的路径
            $zip->addFile($pathfile,basename($pathfile));   //向压缩包中添加文件
        }
        $zip->close();  //关闭压缩包
        $disk = Storage::disk('public');
        $disk->deleteDirectory($dir);
        return response()->download($pathh);                //storage文件中的路径
    }

    /**
     * @return file
     * 激光打标机模板
     */
    public function printLaser(Request $request){
        $id = (int)$request->sid;
        if(!$id) return '';
        //加载模板
        $template_file = './storage/ExcelTemplate/激光打标机.xls'; //考虑到兼容Linux，斜杠用“/”
        if(!file_exists($template_file)) {
            return '模板文件不存在';
        }
        //获取公司名称
        $setting_sys = getCache('setting');
        $setting_info = $setting_sys['setting']; //设置信息
        //样品信息
        $data = DB::table('a_sample_info as a')
            ->leftJoin('a_contract_gaiyao as b', 'b.id', '=', 'a.contract_gaiyao_id')
            ->leftJoin('a_tool as c', 'c.id', '=', 'b.tool_id')
            ->leftJoin('a_tool_class as d', 'd.id', '=', 'c.tool_class_id')
            ->leftJoin('a_contract as e', 'e.id', '=', 'a.contract_id')
            ->leftJoin('a_code2_samplename_map', 'a_code2_samplename_map.name', '=', 'b.tool_name')
            ->select('a.*', 'b.tool_name', 'b.std_num', 'b.class', 'b.voltage', 'e.name_ABC', 'e.created_at', 'a_code2_samplename_map.code', 'd.name as class_name','b.remark')
            ->where('a.id', $id)
            ->orderBy('a.bar_code', 'asc')
            ->first();

        //生成模板
        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file); //读取模板文件
        $worksheet = $spreadsheet->getSheet(0); //按索引获取表单，从 0 开始

        /* ---------------- 二维码 start-------------------- */
        $domain = $request->server('HTTP_HOST'); //域名
        $url_name = 'http://'.$domain."/viewRes?id={$id}&k={$data->key}";
        $qr_code_path = "./QrCodeImage/QrCodeSample{$id}";

        $qrCode = QrCode::format('png');
        $qrCode = $qrCode->size(150);
        $qrCode = $qrCode->margin(0);
        $qrCode->generate($url_name, $qr_code_path);

        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
        $drawing->setPath($qr_code_path);//图片的路径
        $drawing->setHeight(93);//高度 保持宽高比
        $drawing->setOffsetX(5);
        $drawing->setCoordinates('A2');//指定位置
        $drawing->setCoordinates('F8');//指定位置

        // 要将上述图形添加到工作表，请使用以下代码段。PhpSpreadsheet创建绘图和工作表之间的链接：
        $drawing->setWorksheet($worksheet);
        /* ---------------- 二维码 end-------------------- */

        /*----------------- 内容页 ------------------------*/
        $hege = $data->res?'合 格 证':'不 合 格';
        $guige_xinghao = $data->voltage.''.$data->guige_xinghao; //规格型号
        $test_time = date('Y年m月d日',strtotime($data->test_time));
        $next_time = date('Y年m月d日',strtotime($data->next_time));

        $worksheet->getCell('B2')->setValue($setting_info->name_pass);
        $worksheet->getCell('B3')->setValue($hege);
        $worksheet->getCell('B5')->setValue($data->tool_name);
        $worksheet->getCell('B6')->setValue($guige_xinghao);
        $worksheet->getCell('B7')->setValue($data->self_num);
        $worksheet->getCell('B8')->setValue($test_time);
        $worksheet->getCell('B9')->setValue($next_time);
        $worksheet->getCell('B10')->setValue($data->tester_names); //送检单位

        $worksheet->setTitle('合格证');
        //----------直接在浏览器下载----start
        $file_name = $data->tool_name.$data->bar_code."合格证.xls"; //输出的文件名称
        // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
        header('Content-Type: application/vnd.ms-excel'); //告诉浏览器输出Excel 03版本文件
        header('Content-Disposition: attachment;filename='.urlencode($file_name)); //告诉浏览器输出的文件名称
        header('Cache-Control: max-age=0'); //禁止缓存
        //----------直接在浏览器下载----end
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->setPreCalculateFormulas(false); //禁用公式预先计算
        $writer->save('php://output'); //直接在浏览器下载

        //为了防止内存泄露，建议用完手动清理
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        unlink($qr_code_path);//删除二维码图片  节省硬盘空间

    }

    /*自定义打印合格证*/
    public function printPass() {
        // dd(111);
        $setting_info = DB::table('setting')->where('id', '1')->first(); //设置信息
        if(auth('admin')->user()->id === 1) {
            $setting_info->passedcard_remote_ip = '127.0.0.1';
        }
        return view('admin.sampleInfo.printPass', compact('setting_info'));
    }

    //单个审核
    public function oneCheck(Request $request) {
        DB::beginTransaction();
        try {
            $id = (int)$request->id; //sample_info 的 id
            //  update 返回受影响的行数
            $auditman = auth()->user()->realname ? auth()->user()->realname : auth()->user()->username;
            $status0 = $request->status;
            //记录驳回原因
            if($status0 == - 1 && $request->reason !== '') {
                $data_reject = ['sample_info_id' => $id, 'contract_id' => intval($request->batch_id), 'content' => trim($request->reason), 'manager_realname' => $auditman];
                DB::table('a_reject_log')->insert($data_reject);
            }
            $updata = ['status0' => $status0, 'audit_man' => $auditman];
            DB::table('a_sample_info')->where('id', $id)->increment('check_times', 1, $updata);
            $res1 = DB::table('a_item_data')->where('sample_info_id', $id)->update(['commit' => $request->status]);

            $contract_id = $request->batch_id;
            //初次审核时间
            $date = date('Y-m-d H:i:s');
            DB::table('a_sample_info')->where('id', $id)->whereNull('check_time')->update(['check_time' => $date]);
            DB::table('a_status_time')->where('contract_id', $contract_id)->whereNull('check_start')->update(['check_start' => $date]);

            // 审核后检查 未审核通过 的记录数
            $res3 = DB::table('a_sample_info')->where('contract_id', $contract_id)->where('status0', '!=', '2')->count();
            //如果为0，说明本批次已全部审核通过，此时改变contract的状态
            //0-受理中，1-受理完成，5-试验中，8-试验完成，11-审核完成，13-批准驳回，14-批准完成，17-全部检测工作完成，等待退样，20-退样完成
            if($res3 === 0) {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '11']);

                //查询此批次是否记录过审核完成的时间
                $check_end = DB::table('a_status_time')->where('contract_id', $contract_id)->value('check_end');
                if(!$check_end) {
                    # 如果没记录过，就记录审核完成的时间
                    $now_time = date("Y/m/d H:i:s"); //当前时间
                    DB::table('a_status_time')->where('contract_id', $contract_id)->update(['check_end' => $now_time]);
                }
            }
            else {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '8']);
            }
            DB::commit();
        } catch(\Exception $exception) {
            DB::rollBack();
            return '0';
        }

        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //批量审核
    public function batchCheck(Request $request) {
        DB::beginTransaction();
        try {
            $ids = $request->checkID;
            $contract_id = $request->batch_id;
            $auditman = auth()->user()->realname ? auth()->user()->realname : auth()->user()->username;
            //  update 返回受影响的行数
            DB::table('a_sample_info')->whereIn('id', $ids)->increment('check_times', 1, ['status0' => $request->status, 'audit_man' => $auditman]);
            $res1 = DB::table('a_item_data')->whereIn('sample_info_id', $ids)->update(['commit' => $request->status]);

            //初次审核时间
            $date = date('Y-m-d H:i:s');
            DB::table('a_sample_info')->whereIn('id', $ids)->whereNull('check_time')->update(['check_time' => $date]);
            DB::table('a_status_time')->where('contract_id', $contract_id)->whereNull('check_start')->update(['check_start' => $date]);

            // 审核后检查 未审核通过 的记录数
            $res3 = DB::table('a_sample_info')->where('contract_id', $contract_id)->where('status0', '!=', '2')->count();
            //如果为0，说明本批次已全部审核通过，此时改变contract的状态
            if($res3 === 0) {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '11']);

                //查询此批次是否记录过审核完成的时间
                $check_end = DB::table('a_status_time')->where('contract_id', $contract_id)->value('check_end');
                if(!$check_end) {
                    # 如果没记录过，就记录审核完成的时间
                    $now_time = date("Y/m/d H:i:s"); //当前时间
                    DB::table('a_status_time')->where('contract_id', $contract_id)->update(['check_end' => $now_time]);
                }
            }
            else {
                DB::table('a_contract')->where('id', $contract_id)->update(['status' => '8']);
            }
            DB::commit();
        } catch(\Exception $exception) {
            DB::rollBack();
            return '0';
        }
        //由于框架自身不支持响应bool值，所以转化一种形式
        return $res1 >= 0 ? '1' : '0';
    }

    //扫描二维码后，查询样品的基础信息
    public function getInfoById(Request $request) {
        //样品详细信息的id
        $id = $request->id;
        $len = strlen($id);
        if($len > 17) { //rfid
            if($len != 24){
                $id =  substr($id, -18); //四川德阳用的18位码（因为之前的标签存的20位，数据库存的18位，所以这里进行截取）
            }
            $data = DB::table('a_sample_info')->select('self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'gqj_ID', 'bar_code_1st')->where('gqj_ID', $id)->orderBy('ctime', 'desc')->first();
        }
        else {
            $data = DB::table('a_sample_info')->select('self_num', 'guige_xinghao', 'brand', 'manufacturer', 'production_date', 'gqj_ID', 'bar_code_1st')->find($id);
        }
        $res = null;
        if($data) {
            # 查到了结果
            $res = response()->json($data);
        }
        else {
            # 未查到结果
            $res = 'false';
        }
        return $res;
    }

    //图片处理
    public function imgdeal($column, $operate, $bar_code) {
        $photo = DB::table('a_sample_info')->where('bar_code', $bar_code)->value($column);
        if(!$photo) {
            return 0;
        }
        //不合格照片有些地方（如山东淄博千恒）传两张，所以这里用数组处理
        $photos = explode(',',$photo);
        $k = request('k',0);
        $photoOld = data_get($photos,$k,'');
        data_set($photos,$k,'');
        $photo = implode(',', $photos);
        $photo = trim($photo,',');
        $res = DB::table('a_sample_info')->where('bar_code', $bar_code)->update([$column => $photo]);
        if($res && $operate === 'del') {
            @unlink(substr($photoOld, 1));
        }
        return $res;
    }

    //驳回记录
    public function rejectLog($iscontract, $id) {
        $data = [];
        $where = $iscontract == 1 ? ['sample_info_id' => null, 'contract_id' => $id] : ['sample_info_id' => $id];
        $data['list'] = DB::table('a_reject_log')->where($where)->select('content', 'ctime', 'manager_realname')->get();
        return view('admin.sampleInfo.rejectLog', compact('data'));
    }
}
